<template>
  <div class="app-container">
    <div class="filter-container">
      <div style="margin-top: 10px">
        <el-row :gutter="20">
          <el-col :offset="5" :span="13">
            <div class="grid-content bg-purple" style="margin-top: 5px">
              <el-input v-model="keywords">
                <template slot="prepend" class="input-with-select">
                  <el-cascader
                    v-model="nation"
                    :options="nationList"
                    :style="{ width: '100%' }"
                    :props="{ checkStrictly: true }"
                    collapse-tags
                    filterable
                    clearable
                  ></el-cascader>
                </template>
                <template slot="append">
                  <el-button @click="search">
                    {{ $t('dataSearch.search') }}
                  </el-button>
                </template>
              </el-input>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <div class="checkbox-group">
                <p>
                  <el-checkbox v-model="listQuery.hideInvalid">{{
                    $t('dataSearch.hideInvalidCustomer')
                  }}</el-checkbox>
                </p>
                <p>
                  <el-checkbox v-model="listQuery.hideAdded">{{
                    $t('dataSearch.hideAdded')
                  }}</el-checkbox>
                </p>
                <p>
                  <el-checkbox v-model="listQuery.filterDuplicate">{{
                    $t('dataSearch.ignoreDuplicate')
                  }}</el-checkbox>
                </p>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <div>
                <div
                  class="tag-title"
                  style="margin: 5px; display: inline-block"
                >
                  <div
                    style="
                      color: #13ce66;
                      background: #e7faf0;
                      border: 1px solid #a1ebc2;
                      padding: 10px 20px;
                      font-size: 14px;
                      border-radius: 4px;
                    "
                  >
                    {{ $t('dataSearch.filterPlatform') }}
                  </div>
                </div>
                <div class="tag-content inline-block">
                  <el-select
                    v-model="listQuery.filteredPlatforms"
                    clearable
                    multiple
                    style="width: 1000px"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
                <div
                  class="tag-button"
                  style="margin: 5px; display: inline-block"
                >
                  <el-button
                    type="warning"
                    plain
                    size="small"
                    @click="defaultFilter"
                    >{{ $t('dataSearch.defaultFilter') }}</el-button
                  >
                  <el-button
                    type="warning"
                    plain
                    size="small"
                    @click="showAddFilterPlatform"
                    >{{ $t('dataSearch.set') }}</el-button
                  >
                  <el-select
                    size="small"
                    v-model="listQuery.contains"
                    class="w-23 ml-2.5"
                  >
                    <el-option
                      :value="false"
                      :label="$t('dataSearch.exclude')"
                    ></el-option>
                    <el-option
                      :value="true"
                      :label="$t('dataSearch.include')"
                    ></el-option>
                  </el-select>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      default-expand-all
      :height="total > 0 ? 'calc(100vh - 300px)' : 'calc(100vh - 260px)'"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-form
            v-if="row.details"
            label-position="left"
            inline
            class="demo-table-expand"
          >
            <div class="form-group">
              <el-form-item v-if="row.details.facebook_url">
                <template slot="label">
                  <svg-icon name="facebook" style="font-size: 2rem" original />
                </template>
                <el-link
                  target="_blank"
                  :href="row.details.facebook_url"
                  v-html="row.details.facebook_username"
                ></el-link>
              </el-form-item>
              <el-form-item v-if="row.details.twitter_url">
                <template slot="label">
                  <svg-icon name="twitter" style="font-size: 2rem" original />
                </template>
                <el-link target="_blank" :href="row.details.twitter_url">{{
                  row.details.twitter_username
                }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.google_plus_url">
                <template slot="label">
                  <svg-icon
                    name="google-plus"
                    style="font-size: 2rem"
                    original
                  />
                </template>
                <el-link target="_blank" :href="row.details.google_plus_url">{{
                  row.details.google_plus_username
                }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.youtube_url">
                <template slot="label">
                  <svg-icon name="youtube" style="font-size: 2rem" original />
                </template>
                <el-link target="_blank" :href="row.details.youtube_url">{{
                  row.details.youtube_username
                }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.instagram_url">
                <template slot="label">
                  <svg-icon
                    name="instagram"
                    style="font-size: 2rem"
                    color="#f54832 #fff"
                  />
                </template>
                <el-link target="_blank" :href="row.details.instagram_url">{{
                  row.details.instagram_username
                }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.linkedin_url">
                <template slot="label">
                  <svg-icon name="linkedin" style="font-size: 2rem" original />
                </template>
                <el-link target="_blank" :href="row.details.linkedin_url">{{
                  row.details.linkedin_username
                }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.github_url">
                <template slot="label">
                  <svg-icon name="github" style="font-size: 2rem" original />
                </template>
                <el-link target="_blank" :href="row.details.github_url">{{
                  row.details.github_username
                }}</el-link>
              </el-form-item>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('common.id')" width="50">
        <template slot-scope="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('common.domain')"
        min-width="75"
      >
        <template slot-scope="{ row }">
          <el-link target="_blank" :href="row.url">{{ row.domain }}</el-link>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('common.title')"
        min-width="100"
        prop="title"
      />
      <el-table-column
        align="center"
        :label="$t('common.description')"
        min-width="200"
        prop="description"
      />
      <!--      <el-table-column align="left" label="联系电话" min-width="120" prop="details.phones">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <template v-if="row.details && row.details.phones">-->
      <!--            <div v-for="(phone, index) in row.details.phones.split(',')" :key="index">-->
      <!--              <template v-if="index < 5">-->
      <!--                <el-link icon="el-icon-mobile-phone"  @click="handleClipboard(phone, $event)">{{ phone }}</el-link>-->
      <!--              </template>-->
      <!--            </div>-->
      <!--          </template>-->
      <!--          <template v-else>-->
      <!--            暂无信息-->
      <!--          </template>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column align="left" label="邮箱" min-width="180" prop="details.company_email">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <template v-if="row.details && row.details.company_email">-->
      <!--            <div v-for="(email, index) in row.details.company_email.split(',')" :key="index">-->
      <!--              <template v-if="index < 5">-->
      <!--                <el-link icon="el-icon-message"  @click="handleClipboard(email, $event)">{{ email }}</el-link>-->
      <!--              </template>-->
      <!--            </div>-->
      <!--          </template>-->
      <!--          <template v-else>-->
      <!--            暂无信息-->
      <!--          </template>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column align="center" width="290">
        <template slot="header">
          <el-dropdown>
            <span>
              {{ $t('common.batchActions')
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-plus"
                @click.native="batchAddCustomers"
                >{{ $t('dataSearch.batchAdd') }}</el-dropdown-item
              >
              <!--              <el-dropdown-item icon="el-icon-circle-plus"-->
              <!--              >批量挖掘-->
              <!--              </el-dropdown-item-->
              <!--              >-->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="primary"
            plain
            @click="showDetail(row)"
            >{{ $t('common.view') }}</el-button
          >
          <el-button
            type="success"
            size="mini"
            plain
            :disabled="row.isAdded"
            @click="addCustomers(row)"
          >
            {{
              row.isAdded
                ? $t('dataSearch.added')
                : $t('dataSearch.addCustomer')
            }}
          </el-button>
          <!--          <el-button size="mini">深度挖掘</el-button>-->
          <el-button
            plain
            :disabled="row.isInvalid"
            type="danger"
            size="mini"
            @click="addPublicCustomers(row)"
          >
            {{
              row.isInvalid
                ? $t('dataSearch.invalid')
                : $t('dataSearch.invalidCustomer')
            }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="list.length > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      :page-sizes="[10]"
      @pagination="search"
    />
    <add-filter-platform
      :show.sync="showAddFilterPlatformState"
      @submit="handleAddFilterPlatform"
    />
    <Details :show.sync="showDetailsState" :id="selectId"></Details>
  </div>
</template>

<script lang="ts">
import AddFilterPlatform from '@/views/data-search/add-filter-platform.vue'
import {
  getAction,
  getLongTimeAction,
  postAction,
  postLongTimeAction,
} from '@/api/common'
import Details from '@/views/data-search/details.vue'
import Pagination from '@/components/Pagination/index.vue'
import { handleClipboard } from '@/utils/clipboard'
export default {
  name: 'globalEngine',
  components: { Details, AddFilterPlatform, Pagination },
  inject: ['showProgressDialog'],
  data() {
    return {
      list: [],
      total: 0,
      searchLoading: false,
      nationLoading: false,
      listQuery: {
        hideInvalid: true,
        hideAdded: true,
        filterDuplicate: true,
        filteredPlatforms: [''],
        page: 1,
        limit: 10,
        contains: false,
      },
      showAddFilterPlatformState: false,
      showDetailsState: false,
      multipleSelection: [],
      options: [],
      baseOptions: [
        'baidu.com',
        'google.com',
        'bing.com',
        'yahoo.com',
        'facebook.com',
        'aol.com',
        'amazon.com',
        'ebay.com',
        'youtube.com',
        'msn.com',
        'aliexpress.com',
        'alibaba.com',
        'shopee.com',
        'lazada.com',
        'yandex.com',
        'twitter.com',
        'linkedin.com',
        'instagram.com',
      ],
      nation: [],
      keywords: '',
      nationList: [],
      selectId: 0,
      handleClipboard: handleClipboard,
    }
  },
  computed: {
    listLoading() {
      return this.searchLoading || this.nationLoading
    },
  },
  created() {
    this.init()
  },
  watch: {
    '$route.query': {
      deep: true,
      handler(val: any) {
        console.log(val)
        if (val.nation) {
          this.init()
        }
      },
    },
  },
  methods: {
    async init() {
      await this.fetchNationList()
      this.defaultFilter()
      let nation: any = this.$route.query.nation
      const keywords = this.$route.query.keywords
      // let { nation, keywords } = this.$route.query
      if (nation && typeof keywords === 'string') {
        if (typeof nation === 'string')
          nation = nation.split(',').map((m) => parseInt(m))
        this.nation = nation as number[]
        this.keywords = keywords
        this.search()
        // 清除query
        this.$router.push({ query: {} })
      }
    },
    handleSelectionChange(value: any) {
      this.multipleSelection = value
    },
    async search() {
      this.searchLoading = true
      getLongTimeAction(
        {
          nation: this.nation[0],
          keywords: this.keywords,
          ...this.listQuery,
        },
        'globalSearch'
      )
        .then((res) => {
          this.list = res.data.domainList.items
          this.total = res.data.domainList.total
        })
        .finally(() => {
          this.searchLoading = false
        })
      // const _list = []
      // for (const key of Object.keys(res)) {
      //   _list.push(...res[key])
      // }
    },
    async fetchNationList() {
      this.nationLoading = true
      getAction(null, 'globalSearch/GetInit')
        .then((res) => {
          const rec = (m: any): any => {
            if (m.children) {
              return {
                label: m.geoNameCn,
                value: m.id,
                children: m.children.map(rec),
              }
            }
            return { label: m.geoNameCn, value: m.id }
          }
          this.nationList = res.data.nationList?.map(rec) ?? []
        })
        .finally(() => {
          this.nationLoading = false
        })
    },
    async showDetail(row: any) {
      this.showDetailsState = true
      this.selectId = row.id
    },
    addCustomers(row: any) {
      if (this.searchLoading) return
      this.searchLoading = true

      postLongTimeAction(
        null,
        `Customer/DataSearchCreate/${row.id}?isPrivate=1`
      )
        .then((res) => {
          this.$message.success(this.$t('common.operationSuccess'))
          this.search()
        })
        .catch((e) => {
          this.$message.error(e.message)
          this.searchLoading = false
        })
    },
    batchAddCustomers() {
      if (this.searchLoading) return
      this.searchLoading = true

      const selectedRows: number[] = this.multipleSelection.map((m) => m.id)
      if (selectedRows.length === 0) {
        this.$message.warning(
          this.$t('common.select', [this.$t('dataSearch.data')])
        )
        this.searchLoading = false
        return false
      }

      const uploadItems = [
        {
          name: this.$t('dataSearch.data'),
          num: this.multipleSelection.length,
          action: this.batchAddFunc,
          data: this.multipleSelection,
        },
      ]
      const uploadColumns = [
        { label: this.$t('common.domain'), key: 'domain', popover: true },
      ]

      this.showProgressDialog(uploadItems, uploadColumns, this.search, {
        title: this.$t('dataSearch.batchAddCustomer'),
      })
    },
    async batchAddFunc({ item, message }: any) {
      postLongTimeAction(
        null,
        'Customer/DataSearchCreate/' + item.id + '?isPrivate=1'
      )
        .then((res) => {
          message.success(
            '[' + item.domain + '] ' + this.$t('dataSearch.successfulAdd')
          )
        })
        .catch((e) => {
          message.failed('[' + item.domain + '] ' + e.message)
        })
    },
    addPublicCustomers(row: any) {
      if (this.searchLoading) return
      this.searchLoading = true

      postLongTimeAction(null, 'Customer/DataSearchCreate/' + row.id)
        .then((res) => {
          this.$message.success(this.$t('common.operationSuccess'))
          this.search()
        })
        .catch((e) => {
          this.$message.error(e.message)
          this.searchLoading = false
        })
    },
    defaultFilter() {
      this.options = [...this.baseOptions]
      this.listQuery.filteredPlatforms = [...this.options]
    },
    showAddFilterPlatform() {
      this.showAddFilterPlatformState = true
    },
    handleAddFilterPlatform(platforms: string[]) {
      for (const platform of platforms) {
        if (this.options.indexOf(platform) === -1) {
          this.options.push(platform)
          this.listQuery.filteredPlatforms.push(platform)
        }
      }
    },
  },
}
</script>

<style scoped>
.checkbox-group {
  margin-left: 100px;
}

.checkbox-group > p {
  margin: 0px 0px 0px 0px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.el-input::v-deep .el-input-group__prepend {
  padding: 0;
  width: 200px;
  border: unset;
}

.el-cascader::v-deep .e-input {
  margin-top: -1px;
}

/* .el-input::v-deep .el-input-group__prepend >div.el-cascader.el-cascader--medium.el-cascader >div.el-input.el-input--medium.el-input--suffix > .el-input__inner{ */
/* border-right: unset; */
/* } */

.el-table::v-deep .el-table__expanded-cell[class*='cell'] {
  padding: 0;
}
.demo-table-expand::v-deep .el-form-item {
  padding: 20px 0 0;
}
.form-group .el-form-item:first-child {
  padding-left: 30px;
}
</style>
